import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def ageFeature(train_data):
    age_get(train_data)
    age_range(train_data)

def everyFeature(train_data,feature):
    plot_stats(train_data,feature)

def age_get(train_data):
    plt.figure(figsize=(10, 8))
    # 按时偿还贷款的KDE图
    sns.kdeplot(train_data.loc[train_data['loan default'] == 0, 'age'] , label='按时偿还')
    # 没有按时偿还贷款的KDE图
    sns.kdeplot(train_data.loc[train_data['loan default'] == 1, 'age'] , label='未按时偿还')
    plt.legend()
    plt.xlabel('年龄')
    plt.ylabel('密度')
    plt.title('密度的年龄分布')
    plt.show()

def age_range(train_data):
    age_data = train_data[['loan default', 'age']]
    # 年龄属性列分箱
    age_data['YEARS_BINNED'] = pd.cut(age_data['age'], bins=np.linspace(20, 70, num=11))
    age_groups = age_data.groupby('YEARS_BINNED').mean()
    plt.figure(figsize=(8, 8))
    # 分箱后的年龄属性列分项
    plt.bar(age_groups.index.astype(str), 100 * age_groups['loan default'])
    # 标签设置
    plt.xticks(rotation=75)
    plt.xlabel('年龄')
    plt.ylabel('未偿还概率')
    plt.title('未偿还的年龄分布')
    plt.legend()
    plt.show()

def plot_stats(train_data,feature, label_rotation=False, horizontal_layout=True):
    temp = train_data[feature].value_counts()
    df1 = pd.DataFrame({feature: temp.index, '数量': temp.values})

    # 计算每个属性类别中Target=1的个数
    cat_perc = train_data[[feature, 'loan default']].groupby([feature], as_index=False).mean()
    cat_perc.sort_values(by='loan default', ascending=False, inplace=True)

    if (horizontal_layout):
        fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 6))
    else:
        fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(12, 14))
    sns.set_color_codes("pastel")
    s = sns.barplot(ax=ax1, x=feature, y="数量", data=df1)
    if (label_rotation):
        s.set_xticklabels(s.get_xticklabels(), rotation=90)

    s = sns.barplot(ax=ax2, x=feature, y='loan default', order=cat_perc[feature], data=cat_perc)
    if (label_rotation):
        s.set_xticklabels(s.get_xticklabels(), rotation=90)
    plt.ylabel('未偿还贷款率', fontsize=10)
    plt.tick_params(axis='both', which='major', labelsize=10)
    #plt.legend()
    plt.show()